/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : waiting.js                                 
*  Description  : 웨이팅 예약 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-07-27  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	
	
	
	// 2주력
	function clsWeekCalendar()
	{
		this._HTMLDom = null;
		this.sDate = null;
		this.selDate = null;
		
		this._init();
	}
	
	clsWeekCalendar.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content article.reserve_area:first thead");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("th:gt(0)").css("cursor", "pointer");
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setDate: function(newDate){
			this.sDate = newDate;
			this.display();
		}
		, setSelDate: function(newDate){
			this.selDate = newDate;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			var thisClass = this;
			var aWeekday = ["일", "월", "화", "수", "목", "금", "토"];
			
			$layer.find("th:gt(1)").filter("th:not(.th_next)").css("cursor", "pointer").each(function(n){
				var newDate = new Date();
				newDate.setTime(thisClass.sDate.getTime());
				newDate.setDate(newDate.getDate() + n);
				
				$(this).data("date", newDate);
				$(this).find("p:eq(0)").html(aWeekday[newDate.getDay()]);
				$(this).find("p:eq(1)").html(newDate.getDate());
				
				$(this).attr("class", "");
				
				switch(newDate.getDay()){
					case 0:
						$(this).addClass("holiday");
						break;
					case 6:
						$(this).addClass("satday");
						break;
				}
				
				if(thisClass.selDate && newDate.getTime() == thisClass.selDate.getTime()) $(this).addClass("day_over");
			});
		}
		, getDate: function(){
			return this.sDate;
		}
		, getSelDate: function(){
			return this.selDate;
		}
		, getSatIndexs: function(){
			var $layer = this.$getLayer();
			var $sat = $layer.find("th").filter(function(){
				return $(this).hasClass("satday");
			});
			
			return [$layer.find("th:gt(1)").index($sat.eq(0)), $layer.find("th:gt(1)").index($sat.eq(1))];
		}
		, getSunIndexs: function(){
			var $layer = this.$getLayer();
			var $sun = $layer.find("th").filter(function(){
				return $(this).hasClass("holiday");
			});
			
			return [$layer.find("th:gt(1)").index($sun.eq(0)), $layer.find("th:gt(1)").index($sun.eq(1))];
		}
	}
	
	
	
	
	// my설정
	function clsMyConfig()
	{
		this._HTMLDom = null;
		this.szData = null;
		
		this._init();
	}
	
	clsMyConfig.prototype = {
		_init: function(){
			$layer = $("div#container section#main_content div.my_set");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("div.box_txt").hide();
			this.setData("");
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setData: function(szData){
			this.szData = szData;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			
			$layer.find("dl:first dd:first").html(this.szData);
		}
		, toggle: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div.box_txt").toggle();
		}
	}
	
	
	// 날짜별 코스리스트
	function clsCourseTimeList()
	{
		this._HTMLDom = null;
		this.listData = null;
		this.satIndexs = null;
		this.sunIndexs = null;
		
		this._init();
	}
	
	clsCourseTimeList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content article.reserve_area:first tbody");
			this._HTMLDom = {
				"$layer": $layer
				, "$areaElement": $layer.find("tr:first").clone(true)
				, "$element": $layer.find("tr:eq(1)").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(areaData){
			this.listData = areaData;
		}
		, setCourseList: function(courseData){
			for(var i=0;i<this.listData.length;i++){
				this.listData[i]["코스리스트"] = new Array();
			}
			
			for(var i=0;i<courseData.length;i++){
				for(var j=0;j<this.listData.length;j++){
					if(this.listData[j]["지역코드"]+"" == courseData[i]["지역코드"]+"") break;
				}
				if(j < this.listData.length){
					this.listData[j]["코스리스트"].push(courseData[i]);
				}
			}
			
			this.display();
		}
		, setSatIndexs: function(idxs){
			this.satIndexs = idxs;
		}
		, setSunIndexs: function(idxs){
			this.sunIndexs = idxs;
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $areaElement = this._HTMLDom["$areaElement"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.empty();
			for(var i=0;i<this.listData.length;i++){
				var item1 = this.listData[i];
				
				$layer.append($areaElement.clone(true));
				
				if(item1["코스리스트"].length > 0){
					for(j=0;j<item1["코스리스트"].length;j++){
						var item2 = item1["코스리스트"][j];
						
						$layer.append($element.clone(true));
						$layer.find("tr:last td:not(:last)").each(function(n){
							var item3 = item2[n-1];
							
							if(n == 0){
								$(this).html("<em>" + item2["골프장명"] + "</em> " + item2["코스명"]);
							}else{
								$(this).attr("class", "").css({
									"cursor": "pointer"
								});
								$(this).html((item2["리스트"][n-1]["가능여부"]) ? '<img src="../images/btn/btn_waiting.png" alt="waiting">':"");
							}
						});
					}
				}
			}
			
			$layer.find("tr td.area_c").each(function(n){
				$(this).html("[" + thisClass.listData[n]["지역명"] + "]");
			});
			
			$layer.find("tr").has("td:not(.area_c)").find("td:nth-child(" + (this.satIndexs[0]+2) + ")").addClass("satday");
			$layer.find("tr").has("td:not(.area_c)").find("td:nth-child(" + (this.satIndexs[1]+2) + ")").addClass("satday");
			
			$layer.find("tr").has("td:not(.area_c)").find("td:nth-child(" + (this.sunIndexs[0]+2) + ")").addClass("holiday");
			$layer.find("tr").has("td:not(.area_c)").find("td:nth-child(" + (this.sunIndexs[1]+2) + ")").addClass("holiday");
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.hide();
			if($layer.parent().parent().find("div#tmpSpin").length == 0){
				$layer.parent().parent().append("<div id='tmpSpin' style='position:relative; width:700px; height:100px;' />");
			}
			$layer.parent().parent().find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.parent().parent().find("div#tmpSpin").hide().spin(false);
			$layer.show();
		}
		, getAreaKey: function(n){
			for(var i=0;i<this.listData.length;i++){
				var listLen = this.listData[i]["코스리스트"].length;
				
				if(listLen - n < 0){
					n -= listLen;
				}else{
					break;
				}
			}
			
			if(i<this.listData.length){
				return this.listData[i]["지역코드"];
			}else{
				return null;
			}
		}
		, getCourseKey: function(n){
			for(var i=0;i<this.listData.length;i++){
				var listLen = this.listData[i]["코스리스트"].length;
				
				if(listLen - n < 0){
					n -= listLen;
				}else{
					break;
				}
			}
			
			if(i<this.listData.length){
				return this.listData[i]["코스리스트"][n]["코스코드"];
			}else{
				return null;
			}
		}
		, getGolfKey: function(n){
			for(var i=0;i<this.listData.length;i++){
				var listLen = this.listData[i]["코스리스트"].length;
				
				if(listLen - n < 0){
					n -= listLen;
				}else{
					break;
				}
			}
			
			if(i<this.listData.length){
				return this.listData[i]["코스리스트"][n]["골프장코드"];
			}else{
				return null;
			}
		}
	}
	
	
	
	
	
	
	
	
	function clsComm()
	{
		
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		// 웨이팅 예약 리스트
		, getWaitingTimeList: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "WatingreservMainSearchList";
			var options = {
				"dateS": arg["시작일"]
				, "search":  arg["골프장조합"]
			}
			_gf.ajax({
				"sid": "WR001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				var aDate = options["dateS"].split("-");
				
				var sDate = new Date(options["dateS"].substrEx(0,4), options["dateS"].substrEx(4,2)-1, options["dateS"].substrEx(6,2));
				
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						for(j=0;j<res["결과값"].length;j++){
							var tmp1 = res["결과값"][j];
							
							if(tmp1["코스코드"] == obj["courseInfoId"]+"") break;
						}
						
						if(j < res["결과값"].length){
							var tmp2 = res["결과값"][j];
							
							for(var k=0;k<tmp2["리스트"].length;k++){
								if(tmp2["리스트"][k]["예약일"] == obj["reservDate"]+"") break;
							}
							
							if(k<tmp2["리스트"].length){
								tmp2["리스트"][k] = {
									"예약일": obj["reservDate"]+""
								}
							}
						}else{
							res["결과값"].push({
								"지역코드": _util.nvl(obj["region"])
								, "골프장코드": _util.nvl(obj["golfClubId"])
								, "코스코드": _util.nvl(obj["courseInfoId"])
								, "골프장명": _util.nvl(obj["golfClubNm"])
								, "코스명": _util.nvl(obj["courseInfoNm"])
								, "리스트": []
							});
							
							var tmp2 = res["결과값"][res["결과값"].length-1];
							
							var newDate = new Date();
							newDate.setTime(sDate.getTime());
							for(k=0;k<arg["기간"];k++,newDate.setDate(newDate.getDate()+1)){
								var szNewDate = newDate.getFullYear() + ("00" + (newDate.getMonth()+1)).substrEx(-2) + ("00" + newDate.getDate()).substrEx(-2);
								
								if(szNewDate ==obj["reservDate"]+""){
									tmp2["리스트"].push({
										"예약일": obj["reservDate"]+""
										, "가능여부": true
									});
								}else{
									tmp2["리스트"].push({
										"예약일": szNewDate
										, "가능여부": false
									});
								}
							}
						}
					}
				}
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objBookingControl = null;
		this.objWeekCalendar = null;
		this.objMyConfig = null;
		this.objCourseTimeList = null;
		
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objBookingControl = new clsBookingControl();
			this.objWeekCalendar = new clsWeekCalendar();
			this.objMyConfig = new clsMyConfig();
			this.objCourseTimeList = new clsCourseTimeList();
			
			
			this._bind();
			this._beforeStart();
		}
		, _preload: function(){
			_gf.spinStart();

		}
		, _beforeStart: function(){
			var thisClass = this;
			
			this._permitStart = {
				"좌메뉴": false
			}
			
			_util.executeThread(function(){
				return thisClass.objBookingControl.isLoad();
			}, function(){
				thisClass._permitStart["좌메뉴"] = true;
			});
			
			_util.executeThread(function(){
				for(var key in thisClass._permitStart){
					if(!thisClass._permitStart[key]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
			
			
		}
		, _start: function(){
			this.objBookingControl._start(this);
			this.objBookingControl.setReserveType(1);
			
			var areaClone1 = _util.objectCopy(_gf.getAreaCodeData());
			this.objCourseTimeList.setList(areaClone1);
			
			this.objBookingControl.setCalendarDate();
		}
		, _bind: function(){
			var thisClass = this;
			
			// 달력 선택시
			$(this.objBookingControl).on("calendarChange", null, function(){
				thisClass.setCalendarDate();
			});
			
			
			this.objWeekCalendar.$getLayer().on("click", "th:gt(0)", function(){
				var tName = this.tagName.toUpperCase();
				
				switch(tName){
					case "TH":
						var newDate = thisClass.objWeekCalendar.getDate();
						
						// 주력 이전
						if($(this).hasClass("th_prev")){
							newDate.setDate(newDate.getDate()-thisClass.getCalendarPeriod());
							
							//thisClass.objWeekCalendar.setDate(newDate);
							thisClass.objBookingControl.setCalendarDate(newDate);
							//thisClass.objCalendar.setInfo("시작일", newDate);
							//thisClass.reserveSearch();
						// 주력 이후
						}else if($(this).hasClass("th_next")){
							newDate.setDate(newDate.getDate()+thisClass.getCalendarPeriod());
							
							//thisClass.objWeekCalendar.setDate(newDate);
							thisClass.objBookingControl.setCalendarDate(newDate);
							//thisClass.reserveSearch();
						// 주력 날짜 선택
						}else{
							var idx = thisClass.objWeekCalendar.$getLayer().find("th:gt(1)").index($(this));
							
							newDate = new Date();
							newDate.setTime(thisClass.objWeekCalendar.getDate().getTime());
							newDate.setDate(newDate.getDate() + idx);
							
							thisClass.objWeekCalendar.setSelDate(newDate);
							
							// 리스트 페이지 이동
							thisClass.objBookingControl.goWaitingListPage(newDate);
						}

						break;
				}
			});
			
			// 도움말 토글
			this.objMyConfig.$getLayer().on("hover", "img[alt='도움말']", function(){
				thisClass.objMyConfig.toggle();
			});
			
			// 코스별리스트 클릭
			this.objCourseTimeList.$getLayer().on("click", "tr td:not(.area_c):not(.td_cor):not(.td_bl)", function(){
				var n = thisClass.objCourseTimeList.$getLayer().find("tr td:not(.area_c):not(.td_cor):not(.td_bl)").index($(this));
				var rowNum = Math.floor(n / thisClass.getCalendarPeriod());
				var colNum = n % thisClass.getCalendarPeriod();
				
				newDate = new Date();
				newDate.setTime(thisClass.objWeekCalendar.getDate().getTime());
				newDate.setDate(newDate.getDate() + colNum);
				
				var golfKey = thisClass.objCourseTimeList.getGolfKey(rowNum);
				var courseKey = thisClass.objCourseTimeList.getCourseKey(rowNum);
				var areaKey = thisClass.objCourseTimeList.getAreaKey(rowNum);
				
				thisClass.objBookingControl.goWaitingListPage(newDate, {
					"골프장코드": golfKey
					, "코스코드": courseKey
					, "지역코드": areaKey
				});
			});
		}
		// 달력선택
		, setCalendarDate: function(){
			var newDate = this.objBookingControl.getCalendarDate();
			
			//주력에 전달
			this.objWeekCalendar.setDate(newDate);
			
			// 검색
			//this.date_reserve();
			this.reserveSearch();
		}
		// 검색
		, reserveSearch: function(){
			var thisClass = this;
			
			this.objCourseTimeList.setSatIndexs(this.objWeekCalendar.getSatIndexs());
			this.objCourseTimeList.setSunIndexs(this.objWeekCalendar.getSunIndexs());
			
			this.objCourseTimeList.spinStart();
			
			var szGolf = this.objBookingControl.getAreaGolfValues();
			var sDate = this.objBookingControl.getCalendarDate();
			
			this.objComm.getWaitingTimeList({
				"골프장조합": szGolf
				, "시작일": sDate.getFullYear() + ("00" + (sDate.getMonth()+1)).substrEx(-2) + ("00" + sDate.getDate()).substrEx(-2)
				, "기간": this.getCalendarPeriod()
				, "콜백": function(ret){
					thisClass.finishWaitingTimeList(ret);
				}
			});
		}
		// 웨이팅 예약 리스트 완료
		, finishWaitingTimeList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objCourseTimeList.spinEnd();
			
			this.objCourseTimeList.setCourseList(ret["결과값"]);
		}
	}
	
	$.ajax({
		url: _ROOT + "/booking/js/booking_common.js"
		, type: "get"
		, dataType: "script"
		, async: false
		, success: function(ret){
			document.objControl = new clsControl();
			document.objControl._init();
		}
		, error: function(){
			alert("error");
		}
	});
	
	
});
